import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { UserType } from '@/apis/components/userType'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { mergeCartApi } from '@/apis/cart'
import { useCartListStore } from './cartList'

export const useUserStore = defineStore(
  'user',
  () => {
    const router = useRouter()
    const cartListStore = useCartListStore()
    // 用户信息
    const userInfo = ref<UserType>()
    // token
    const token = ref('')

    // 从本地获取用户信息和token
    const getUserinfoAndToken = () => {
      userInfo.value = JSON.parse(localStorage.getItem('userInfo') || '{}') || {}
      token.value = JSON.parse(localStorage.getItem('token') || '') || ''
    }
    getUserinfoAndToken()

    // 登录成功
    const loginSuccess = async (info: UserType) => {
      // 保存用户信息和token
      userInfo.value = info
      token.value = info.token
      // 本地保存用户信息和token
      localStorage.setItem('userInfo', JSON.stringify(info))
      localStorage.setItem('token', JSON.stringify(info.token))
      router.push('/')
      ElMessage.success('登录成功')
      // 登录后需要把本地购物车合并，且清空本地购物车
      await mergeCartApi(cartListStore.cartList)
      cartListStore.clearLocalCart()
    }

    // 退出登录
    const exitLogin = () => {
      // 清空用户信息和token
      localStorage.setItem('userInfo', JSON.stringify({}))
      localStorage.setItem('token', JSON.stringify(''))

      getUserinfoAndToken()

      router.push('/login')
      ElMessage.success('退出登录成功')
    }

    return { userInfo, token, loginSuccess, exitLogin }
  },
  // {
  //   persist: true,
  // },
)
